#include "../include/thread_pool.h"

int tcpInit(const char * ip, const char * port){
    // 创建tcp的监听套接字
    int sockfd = socket(AF_INET,SOCK_STREAM,0);
    printf("listenfd: %d\n",sockfd);
    if(sockfd < 0){
        perror("socket");
        return -1;
    }
    int flag = 1;
    int ret = setsockopt(sockfd,SOL_SOCKET,SO_REUSEADDR,&flag,sizeof(flag));
    if(ret < 0){
        perror("setsockopt");
        close(sockfd);
        return -1;
    }

    // 绑定网络
    struct sockaddr_in addr;
    addr.sin_family = AF_INET;
    addr.sin_port = htons(atoi(port));
    addr.sin_addr.s_addr = inet_addr(ip);

    ret = bind(sockfd,(struct sockaddr *)&addr,sizeof(addr));
    if(ret < 0){
        perror("bind");
        close(sockfd);
        return -1;
    }

    ret = listen(sockfd,50);
    if(ret < 0){
        perror("listen");
        close(sockfd);
        return -1;
    }
    printf("server start listening.\n");

    return sockfd;
}


int addEpollReadfd(int epfd, int fd){
    struct epoll_event evt;
    memset(&evt, 0, sizeof(evt));
    evt.data.fd = fd;
    evt.events = EPOLLIN;
    int ret = epoll_ctl(epfd, EPOLL_CTL_ADD, fd, &evt);
    ERROR_CHECK(ret, -1, "epoll_ctl");
    return 0;
}


int delEpollReadfd(int epfd, int fd){
    struct epoll_event evt;
    memset(&evt, 0, sizeof(evt));
    evt.data.fd = fd;
    evt.events = EPOLLIN;
    int ret = epoll_ctl(epfd, EPOLL_CTL_DEL, fd, &evt);
    ERROR_CHECK(ret, -1, "epoll_ctl");
    return 0;
}



int sendn(int sockfd, const void * buff, int len){
    int left = len;
    const char * pbuf = (const char*)buff;
    int ret = -1;
    while(left > 0) {
        ret = send(sockfd, pbuf, left, 0);
        if(ret < 0) {
            perror("send");
            return -1;
        }

        left -= ret;
        pbuf += ret;
    }
    return len - left;
}



int recvn(int sockfd, void * buff, int len){
    int left = len;//还剩下多少个字节需要接收
    char * pbuf = (char*)buff;
    int ret = -1;
    while(left > 0) {
        ret = recv(sockfd, pbuf, left, 0);
        if(ret == 0) {
            break;
        } else if(ret < 0) {
            perror("recv");
            return -1;
        }

        left -= ret;
        pbuf += ret;
    }
    //当退出while循环时，left的值等于0
    return len - left;
}

